import pytest
import pandas as pd
from datetime import datetime
from infrastructure.model.base_model import BaseModel
from infrastructure.database.database_context import DatabaseContext
from sqlalchemy import Column, String, DateTime, INT


class TestModel(BaseModel):
    """用于测试的具体模型类"""
    __tablename__ = 'test_model'

    id = Column(INT, primary_key=True)
    name = Column(String)
    created_at = Column(DateTime)


class TestBaseModel:
    @pytest.fixture
    def sample_df(self):
        """创建测试用的DataFrame"""
        test_data = {
            'id': [1, 2],
            'name': ['test1', 'test2'],
            'created_at': [datetime.now(), datetime.now()]
        }
        return pd.DataFrame(test_data)

    def test_save_dataframe(self, sample_df):
        """测试保存DataFrame数据"""
        # 使用index_elements和if_exists='append'来处理重复ID
        result = TestModel.save(sample_df, if_exists='append', index_elements=['id'])
        assert result is True

    def test_save_empty_dataframe(self):
        """测试保存空DataFrame"""
        df = pd.DataFrame()
        result = TestModel.save(df)
        assert result is True

    def test_save_with_index_elements(self, sample_df):
        """测试使用index_elements保存数据"""
        result = TestModel.save(sample_df, if_exists='append', index_elements=['id'])
        assert result is True

    def test_to_dataframe(self):
        """测试查询结果转换为DataFrame"""
        test_model = TestModel(id=1, name='test', created_at=datetime.now())
        df = TestModel.to_dataframe([test_model])
        assert isinstance(df, pd.DataFrame)
        assert len(df) == 1
        assert 'id' in df.columns
        assert 'name' in df.columns

    def test_find_all(self, monkeypatch):
        """测试获取所有记录"""
        results = TestModel.find_all()
        assert isinstance(results, list)

    def test_find_by_id(self):
        """测试根据ID获取记录"""
        result = TestModel.find_by_id(1)
        assert result is None

    def test_find_all_by_ids(self):
        """测试根据ID列表获取记录"""
        ids = [1, 2]
        results = TestModel.find_all_by_id(ids)
        assert isinstance(results, list)

    def test_save_model(self):
        """测试保存单个模型实例"""
        test_model = TestModel(id=1, name='test', created_at=datetime.now())

        # 模拟成功的情况
        result = TestModel.save_model(test_model)
        assert isinstance(result, TestModel)

    def test_delete_model(self):
        """测试删除单个模型实例"""
        test_model = TestModel.find_by_id(1)

        # 模拟成功的情况
        TestModel.delete(test_model)

    def test_delete_all(self):
        """测试删除所有模型实例"""
        # 模拟成功的情况
        TestModel.delete_by_id(2)

    def test_delete_all_by_ids(self):
        """测试根据ID列表批量删除"""
        ids = [1, 2, 3]
        TestModel.delete_all_by_id(ids)

    def test_update_model(self):
        """测试更新单个模型实例"""
        test_model = TestModel.find_by_id(3)
        test_model.name = 'updated_test'

        # 模拟成功的情况
        TestModel.update(test_model)

